<template>
  <div class="student-id-container">
    <el-card>
      <template #header>
        <span>学生账号管理</span>
      </template>
      
      <el-tabs v-model="activeTab" class="management-tabs">
        <!-- 学生账号管理标签页 -->
        <el-tab-pane label="学生账号管理" name="account">
          <div class="account-management-content">
            <!-- 搜索和操作栏 -->
            <div class="toolbar">
              <el-row :gutter="16">
                <el-col :span="8">
                  <el-input
                    v-model="searchForm.keyword"
                    placeholder="请输入学号或姓名搜索"
                    clearable
                    @clear="handleSearch"
                    @keyup.enter="handleSearch"
                  >
                    <template #prefix>
                      <el-icon><Search /></el-icon>
                    </template>
                    <template #append>
                      <el-button @click="handleSearch">查询</el-button>
                    </template>
                  </el-input>
                </el-col>
                <el-col :span="4">
                  <el-button type="primary" @click="handleAdd">
                    <el-icon><Plus /></el-icon>
                    添加账号
                  </el-button>
                </el-col>
                <el-col :span="4">
                  <el-button type="danger" :disabled="selectedRows.length === 0" @click="handleBatchDelete">
                    <el-icon><Delete /></el-icon>
                    批量删除
                  </el-button>
                </el-col>
              </el-row>
            </div>

            <!-- 账号列表表格 -->
            <div class="table-section">
              <el-table
                v-loading="loading"
                :data="accountList"
                stripe
                style="width: 100%"
                @selection-change="handleSelectionChange"
                @row-click="handleRowClick"
                :empty-text="'暂无账号数据'"
              >
                <el-table-column type="selection" width="55" align="center" />
                <el-table-column prop="studentNum" label="学号" width="140" align="left" />
                <el-table-column prop="name" label="姓名" width="120" align="left" />

                <el-table-column prop="phone" label="手机号" width="140" align="left" />
                <el-table-column prop="className" label="班级" width="180" align="left" />
                <el-table-column prop="status" label="状态" width="100" align="center">
                  <template #default="{ row }">
                    <el-tag :type="row.status === '正常' ? 'success' : 'danger'" size="small">
                      {{ row.status }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="createTime" label="创建时间" width="180" align="left" />
                <el-table-column label="操作" width="200" align="center" fixed="right">
                  <template #default="{ row }">
                    <el-button type="primary" size="small" link @click="handleEdit(row)">
                      编辑
                    </el-button>
                    <el-button type="warning" size="small" link @click="handleResetPassword(row)">
                      重置密码
                    </el-button>
                    <el-button type="danger" size="small" link @click="handleDelete(row)">
                      删除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>

              <!-- 分页 -->
              <div class="pagination-section">
                <el-pagination
                  v-model:current-page="pagination.currentPage"
                  v-model:page-size="pagination.pageSize"
                  :page-sizes="[10, 20, 50, 100]"
                  :total="pagination.total"
                  layout="total, sizes, prev, pager, next, jumper"
                  @size-change="handleSizeChange"
                  @current-change="handlePageChange"
                />
              </div>
            </div>
          </div>
        </el-tab-pane>

        <!-- 学生信息审核标签页 -->
        <el-tab-pane label="学生信息审核" name="audit">
          <div class="audit-management-content">
            <!-- 筛选栏 -->
            <div class="toolbar">
              <el-row :gutter="16">
                <el-col :span="8">
                  <el-input
                    v-model="auditSearchForm.keyword"
                    placeholder="请输入学号或姓名搜索"
                    clearable
                    @clear="handleAuditSearch"
                    @keyup.enter="handleAuditSearch"
                  >
                    <template #prefix>
                      <el-icon><Search /></el-icon>
                    </template>
                    <template #append>
                      <el-button @click="handleAuditSearch">查询</el-button>
                    </template>
                  </el-input>
                </el-col>
                <el-col :span="6">
                  <el-select v-model="auditSearchForm.status" placeholder="审核状态" clearable @change="handleAuditSearch">
                    <el-option label="待审核" value="pending" />
                    <el-option label="已通过" value="approved" />
                    <el-option label="已拒绝" value="rejected" />
                  </el-select>
                </el-col>
              </el-row>
            </div>

            <!-- 审核列表表格 -->
            <div class="table-section">
              <el-table
                :data="auditList"
                stripe
                style="width: 100%"
                :empty-text="'暂无待审核信息'"
              >
                <el-table-column prop="studentNum" label="学号" width="140" align="left" />
                <el-table-column prop="name" label="姓名" width="120" align="left" />
                <el-table-column prop="field" label="审核字段" width="150" align="left">
                  <template #default="{ row }">
                    <el-tag type="info" size="small">{{ getFieldName(row.field) }}</el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="oldValue" label="原值" width="150" align="left" />
                <el-table-column prop="newValue" label="新值" width="150" align="left" />
                <el-table-column prop="problemMsg" label="问题描述" width="200" align="left" show-overflow-tooltip />
                <el-table-column prop="status" label="审核状态" width="120" align="center">
                  <template #default="{ row }">
                    <el-tag :type="getAuditStatusType(row.status)" size="small">
                      {{ getAuditStatusName(row.status) }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="submitTime" label="提交时间" width="180" align="left" />
                <el-table-column label="操作" width="200" align="center" fixed="right">
                  <template #default="{ row }">
                    <el-button
                      v-if="row.status === 'pending'"
                      type="success"
                      size="small"
                      @click="handleApprove(row)"
                    >
                      通过
                    </el-button>
                    <el-button
                      v-if="row.status === 'pending'"
                      type="danger"
                      size="small"
                      @click="handleReject(row)"
                    >
                      拒绝
                    </el-button>
                    <el-button type="primary" size="small" link @click="handleViewDetail(row)">
                      详情
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>

              <!-- 分页 -->
              <div class="pagination-section">
                <el-pagination
                  v-model:current-page="auditPagination.currentPage"
                  v-model:page-size="auditPagination.pageSize"
                  :page-sizes="[10, 20, 50, 100]"
                  :total="auditPagination.total"
                  layout="total, sizes, prev, pager, next, jumper"
                  @size-change="handleAuditSizeChange"
                  @current-change="handleAuditPageChange"
                />
              </div>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加/编辑账号对话框 -->
    <el-dialog
      v-model="accountDialogVisible"
      :title="accountDialogTitle"
      width="600px"
      @close="handleDialogClose"
    >
      <el-form
        ref="accountFormRef"
        :model="accountForm"
        :rules="accountRules"
        label-width="100px"
      >
        <el-form-item label="姓名" prop="name">
          <el-input v-model="accountForm.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="学号" prop="studentNum">
          <el-input v-model="accountForm.studentNum" placeholder="请输入学号" />
        </el-form-item>
        <el-form-item label="学院" prop="grade">
          <el-select v-model="accountForm.grade" placeholder="请选择学院" style="width: 100%">
            <el-option label="数学与计算机学院" value="数学与计算机学院" />
            <el-option label="经济管理学院" value="经济管理学院" />
            <el-option label="水产学院" value="水产学院" />
          </el-select>
        </el-form-item>
        <el-form-item label="班级" prop="className">
          <el-input v-model="accountForm.className" placeholder="请输入班级" />
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="accountForm.phone" placeholder="请输入电话" />
        </el-form-item>
        <el-form-item label="备注" prop="problemMsg">
          <el-input 
            v-model="accountForm.problemMsg" 
            type="textarea" 
            :rows="3"
            placeholder="请输入备注" 
          />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="accountForm.email" placeholder="请输入邮箱" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="accountDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="handleSubmitAccount">
          确定
        </el-button>
      </template>
    </el-dialog>

    <!-- 审核详情对话框 -->
    <el-dialog
      v-model="auditDetailDialogVisible"
      title="审核详情"
      width="600px"
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="学号">{{ currentAuditDetail.studentNum }}</el-descriptions-item>
        <el-descriptions-item label="姓名">{{ currentAuditDetail.name }}</el-descriptions-item>
        <el-descriptions-item label="审核字段">{{ getFieldName(currentAuditDetail.field) }}</el-descriptions-item>
        <el-descriptions-item label="审核状态">
          <el-tag :type="getAuditStatusType(currentAuditDetail.status)" size="small">
            {{ getAuditStatusName(currentAuditDetail.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="原值" :span="2">{{ currentAuditDetail.oldValue }}</el-descriptions-item>
        <el-descriptions-item label="新值" :span="2">{{ currentAuditDetail.newValue }}</el-descriptions-item>
        <el-descriptions-item label="问题描述" :span="2">{{ currentAuditDetail.problemMsg }}</el-descriptions-item>
        <el-descriptions-item label="提交时间">{{ currentAuditDetail.submitTime }}</el-descriptions-item>
        <el-descriptions-item label="审核时间">{{ currentAuditDetail.auditTime || '未审核' }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <el-button @click="auditDetailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { Search, Plus, Delete } from '@element-plus/icons-vue'
import { getStudentList, createStudent, deleteStudent, type StudentListItem, type CreateStudentRequest } from '../../api/studentInfo'

const router = useRouter()

const activeTab = ref('account')
const accountDialogVisible = ref(false)
const auditDetailDialogVisible = ref(false)
const accountDialogTitle = ref('添加账号')
const submitLoading = ref(false)
const accountFormRef = ref<FormInstance>()
const selectedRows = ref<any[]>([])
const loading = ref(false)

// 搜索表单
const searchForm = reactive({
  keyword: ''
})

const auditSearchForm = reactive({
  keyword: '',
  status: ''
})

// 账号列表数据（所有数据）
const allAccountList = ref<any[]>([])

// 计算当前页显示的数据
const accountList = computed(() => {
  const start = (pagination.currentPage - 1) * pagination.pageSize
  const end = start + pagination.pageSize
  return allAccountList.value.slice(start, end)
})

// 原始学生数据（保存完整的API返回数据）
const rawStudentDataMap = ref<Map<number | string, StudentListItem>>(new Map())

// 审核列表数据
const auditList = ref([
  {
    id: 1,
    studentNum: '2024001',
    name: '张三',
    field: 'name',
    oldValue: '张三',
    newValue: '张三三',
    problemMsg: '姓名格式不正确',
    status: 'pending',
    submitTime: '2024-01-15 10:00:00'
  },
  {
    id: 2,
    studentNum: '2024002',
    name: '李四',
    field: 'phone',
    oldValue: '13800138002',
    newValue: '13900139002',
    problemMsg: '',
    status: 'approved',
    submitTime: '2024-01-14 10:00:00',
    auditTime: '2024-01-14 11:00:00'
  }
])

// 分页配置
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

const auditPagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 账号表单
const accountForm = reactive({
  name: '',
  studentNum: '',
  grade: '',
  className: '',
  phone: '',
  problemMsg: '',
  email: ''
})

// 账号表单验证规则
const accountRules: FormRules = {
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' }
  ],
  studentNum: [
    { required: true, message: '请输入学号', trigger: 'blur' },
    {
      validator: (_rule, value, callback) => {
        if (!value) {
          callback()
          return
        }
        // 学号必须为12位
        if (value.length !== 12) {
          callback(new Error('学号必须为12位'))
          return
        }
        // 学号前四位必须为年份（4位数字）
        const yearPart = value.substring(0, 4)
        if (!/^\d{4}$/.test(yearPart)) {
          callback(new Error('学号前四位必须为年份（4位数字）'))
          return
        }
        // 学号必须全为数字
        if (!/^\d{12}$/.test(value)) {
          callback(new Error('学号必须全为数字'))
          return
        }
        // 年份范围验证（例如：2000-2099）
        const year = parseInt(yearPart)
        if (year < 2000 || year > 2099) {
          callback(new Error('学号前四位年份应在2000-2099之间'))
          return
        }
        callback()
      },
      trigger: 'blur'
    }
  ],
  grade: [
    { required: true, message: '请选择学院', trigger: 'change' }
  ],
  className: [
    { required: true, message: '请输入班级', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ]
}

// 当前审核详情
const currentAuditDetail = reactive({
  studentNum: '',
  name: '',
  field: '',
  oldValue: '',
  newValue: '',
  problemMsg: '',
  status: '',
  submitTime: '',
  auditTime: ''
})

// 搜索
const handleSearch = () => {
  // TODO: 实现搜索逻辑
  ElMessage.info('搜索功能开发中...')
}

// 添加账号
const handleAdd = () => {
  accountDialogTitle.value = '添加账号'
  accountForm.name = ''
  accountForm.studentNum = ''
  accountForm.grade = ''
  accountForm.className = ''
  accountForm.phone = ''
  accountForm.problemMsg = ''
  accountForm.email = ''
  accountDialogVisible.value = true
}

// 编辑账号（跳转到详情页进行编辑）
const handleEdit = (row: any) => {
  // 从原始数据中获取完整的学生信息
  const rawData = rawStudentDataMap.value.get(row.id)
  if (rawData) {
    // 将完整的学生信息存储到 sessionStorage
    sessionStorage.setItem('currentStudentDetail', JSON.stringify(rawData))
  }
  
  router.push({
    name: 'student-detail',
    params: { id: row.id }
  })
}

// 删除账号
const handleDelete = async (row: any) => {
  try {
    await ElMessageBox.confirm(`确定要删除账号 "${row.name}" 吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // 从原始数据中获取 userId
    const rawData = rawStudentDataMap.value.get(row.id)
    if (!rawData) {
      ElMessage.error('无法获取学生数据，无法删除')
      return
    }
    
    // 检查 userId 是否存在（允许 0 值）
    if (rawData.userId === undefined || rawData.userId === null) {
      ElMessage.error('无法获取用户ID，无法删除')
      return
    }

    const userId = rawData.userId
    // 确保 userId 是数字类型
    const userIdNum = typeof userId === 'string' ? parseInt(userId) : userId
    
    if (isNaN(userIdNum)) {
      ElMessage.error('用户ID格式不正确')
      return
    }
    
    // 调用删除接口，使用 userId
    const response = await deleteStudent(userIdNum)
    const responseCode = String(response.code)
    
    if (responseCode === '200' || responseCode === '0') {
      ElMessage.success('删除成功')
      // 重新加载学生列表
      await fetchStudentList()
    } else {
      ElMessage.error(response.msg || '删除失败，请重试')
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('删除学生失败:', error)
      ElMessage.error(error.message || '删除失败，请稍后重试')
    }
  }
}

// 批量删除
const handleBatchDelete = async () => {
  try {
    await ElMessageBox.confirm(`确定要删除选中的 ${selectedRows.value.length} 个账号吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // 批量删除：逐个调用删除接口，使用 userId
    const deletePromises = selectedRows.value.map(async (row) => {
      const rawData = rawStudentDataMap.value.get(row.id)
      if (rawData && (rawData.userId !== undefined || rawData.userId === 0)) {
        const userId = rawData.userId
        // 确保 userId 是数字类型
        const userIdNum = typeof userId === 'string' ? parseInt(userId) : userId
        if (!isNaN(userIdNum)) {
          return deleteStudent(userIdNum)
        }
      }
      return null
    })

    const results = await Promise.all(deletePromises.filter(p => p !== null))
    
    // 检查是否有失败的删除
    const failedCount = results.filter(r => r && r.code !== '200' && r.code !== '0').length
    const successCount = results.length - failedCount

    if (failedCount === 0) {
      ElMessage.success(`成功删除 ${successCount} 个账号`)
      selectedRows.value = []
      // 重新加载学生列表
      await fetchStudentList()
    } else {
      ElMessage.warning(`成功删除 ${successCount} 个账号，${failedCount} 个删除失败`)
      // 即使有失败的，也重新加载列表以更新数据
      await fetchStudentList()
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('批量删除失败:', error)
      ElMessage.error(error.message || '批量删除失败，请稍后重试')
    }
  }
}

// 重置密码
const handleResetPassword = async (row: any) => {
  try {
    await ElMessageBox.confirm(`确定要重置账号 "${row.name}" 的密码吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    // TODO: 调用重置密码接口
    ElMessage.success('密码重置成功，新密码已发送至邮箱')
  } catch {
    // 用户取消
  }
}

// 提交账号表单
const handleSubmitAccount = async () => {
  if (!accountFormRef.value) return
  
  await accountFormRef.value.validate(async (valid) => {
    if (valid) {
      submitLoading.value = true
      try {
        // 获取当前登录用户信息
        const userInfoStr = localStorage.getItem('userInfo')
        let createBy = 1 // 默认值
        if (userInfoStr) {
          try {
            const userInfo = JSON.parse(userInfoStr)
            createBy = userInfo.id || userInfo.userId || 1
          } catch (e) {
            console.warn('解析用户信息失败:', e)
          }
        }

        // 构建创建学生请求数据，其他字段为空或默认值
        const createData: CreateStudentRequest = {
          id: 0, // 添加时ID为0
          userId: 0, // 添加时userId为0
          name: accountForm.name,
          studentNum: accountForm.studentNum,
          grade: accountForm.grade,
          className: accountForm.className,
          phone: accountForm.phone,
          problemMsg: accountForm.problemMsg || '',
          email: accountForm.email || '',
          gpa: 0,
          indiscipline: 0,
          nameCheckStatus: 0,
          studentNumCheckStatus: 0,
          classCheckStatus: 0,
          phoneCheckStatus: 0,
          status: 1, // 默认状态为正常
          createTime: new Date().toISOString(),
          updateTime: '',
          createBy: createBy,
          updateBy: 0
        }

        const response = await createStudent(createData)
        
        if (response.code === '200') {
          ElMessage.success('添加成功')
          accountDialogVisible.value = false
          // 重新加载学生列表
          await fetchStudentList()
        } else {
          ElMessage.error(response.msg || '添加失败')
        }
      } catch (error) {
        console.error('添加学生失败:', error)
        ElMessage.error('添加失败，请稍后重试')
      } finally {
        submitLoading.value = false
      }
    }
  })
}

// 关闭对话框
const handleDialogClose = () => {
  accountFormRef.value?.resetFields()
}

// 表格选择变化
const handleSelectionChange = (selection: any[]) => {
  selectedRows.value = selection
}

// 表格行点击事件
const handleRowClick = (row: any) => {
  // 从原始数据中获取完整的学生信息
  const rawData = rawStudentDataMap.value.get(row.id)
  if (rawData) {
    // 将完整的学生信息存储到 sessionStorage
    sessionStorage.setItem('currentStudentDetail', JSON.stringify(rawData))
  }
  
  router.push({
    name: 'student-detail',
    params: { id: row.id }
  })
}

// 分页
const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  pagination.currentPage = 1 // 改变每页数量时重置到第一页
}

const handlePageChange = (page: number) => {
  pagination.currentPage = page
}

// 审核相关
const handleAuditSearch = () => {
  // TODO: 实现审核搜索逻辑
  ElMessage.info('搜索功能开发中...')
}

const getFieldName = (field: string) => {
  const fieldMap: Record<string, string> = {
    name: '姓名',
    studentNum: '学号',
    phone: '手机号',
    className: '班级'
  }
  return fieldMap[field] || field
}

const getAuditStatusType = (status: string) => {
  const statusMap: Record<string, string> = {
    pending: 'warning',
    approved: 'success',
    rejected: 'danger'
  }
  return statusMap[status] || ''
}

const getAuditStatusName = (status: string) => {
  const statusMap: Record<string, string> = {
    pending: '待审核',
    approved: '已通过',
    rejected: '已拒绝'
  }
  return statusMap[status] || status
}

const handleApprove = async (row: any) => {
  try {
    await ElMessageBox.confirm('确定要通过该审核吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'info'
    })
    // TODO: 调用审核通过接口
    row.status = 'approved'
    row.auditTime = new Date().toLocaleString()
    ElMessage.success('审核通过')
  } catch {
    // 用户取消
  }
}

const handleReject = async (row: any) => {
  try {
    await ElMessageBox.confirm('确定要拒绝该审核吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    // TODO: 调用审核拒绝接口
    row.status = 'rejected'
    row.auditTime = new Date().toLocaleString()
    ElMessage.success('已拒绝')
  } catch {
    // 用户取消
  }
}

const handleViewDetail = (row: any) => {
  Object.assign(currentAuditDetail, row)
  auditDetailDialogVisible.value = true
}

const handleAuditSizeChange = (size: number) => {
  auditPagination.pageSize = size
  // TODO: 重新加载数据
}

const handleAuditPageChange = (page: number) => {
  auditPagination.currentPage = page
  // TODO: 重新加载数据
}

// 获取学生列表
const fetchStudentList = async () => {
  loading.value = true
  try {
    const response = await getStudentList({
      name: '',
      gender: '',
      studentNum: '',
      grade: '',
      className: ''
    })
    
    if (response.code === '200' && response.data) {
      // 清空原始数据映射
      rawStudentDataMap.value.clear()
      
      // 将API返回的数据映射到账号列表格式，并保存原始数据
      allAccountList.value = response.data.map((item: StudentListItem) => {
        const id = typeof item.id === 'number' ? item.id : (typeof item.id === 'string' ? parseInt(item.id) || 0 : 0)
        
        // 保存原始完整数据
        if (id) {
          rawStudentDataMap.value.set(id, item)
        }
        
        // 格式化创建时间
        let createTimeStr = ''
        if (item.createTime) {
          try {
            const date = new Date(item.createTime)
            createTimeStr = date.toLocaleString('zh-CN', {
              year: 'numeric',
              month: '2-digit',
              day: '2-digit',
              hour: '2-digit',
              minute: '2-digit',
              second: '2-digit',
              hour12: false
            }).replace(/\//g, '-')
          } catch (e) {
            createTimeStr = item.createTime
          }
        }
        
        return {
          id: id,
          studentNum: item.studentNum || item.studentId || '',
          name: item.name || '',
          username: item.studentNum || item.studentId || '', // 默认使用学号作为用户名
          email: '', // API返回的数据中可能没有邮箱
          phone: item.phone || item.contact || '',
          className: item.className || item.class || '',
          status: item.status === 1 ? '正常' : '禁用', // 根据status字段判断
          createTime: createTimeStr
        }
      })
      
      // 更新分页总数
      pagination.total = allAccountList.value.length
      // 重置到第一页
      pagination.currentPage = 1
    } else {
      ElMessage.warning(response.msg || '获取学生列表失败')
      allAccountList.value = []
      pagination.total = 0
    }
  } catch (error) {
    console.error('获取学生列表失败:', error)
    ElMessage.error('获取学生列表失败，请稍后重试')
    allAccountList.value = []
    pagination.total = 0
  } finally {
    loading.value = false
  }
}

// 页面加载时获取学生列表
onMounted(() => {
  fetchStudentList()
})
</script>

<style scoped>
.student-id-container {
  padding: 0;
}

.management-tabs {
  margin-top: 20px;
}

.account-management-content,
.audit-management-content {
  padding: 20px 0;
}

.toolbar {
  margin-bottom: 20px;
  padding-bottom: 20px;
  border-bottom: 1px solid #f0f0f0;
}

.table-section {
  margin-top: 20px;
}

.pagination-section {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>